package com.icez.base_util_library

import android.app.Activity
import android.content.*
import android.content.pm.ActivityInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.res.Resources
import android.graphics.Point
import android.graphics.Rect
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.core.content.FileProvider
import java.io.File
import java.io.IOException
import java.lang.reflect.Method
import java.text.SimpleDateFormat
import java.util.*

/**
 * @author icez
 *  系统工具类
 */
class SystemUtil {
    companion object{
        //android 包名
        val ANDROID_OS_PACKAGE = "android"
        //状态栏高度ID
        val STATUS_BAR_HEIGHT = "status_bar_height"
        //底部状态栏高度
        val NAVIGATION_BAR_HEIGHT = "navigation_bar_height"

        val instance:SystemUtil by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED){
            SystemUtil()
        }
        val REQUEST_IMAGE_CAPTURE = 1
    }

    /**
     *  获取状态栏的高度
     * @param context 上下文
     */
    public fun getStatusBarHeight(context: Context): Int {
        val resId = ResourcesUtil.instance.getResourcesId(context,
            STATUS_BAR_HEIGHT,ResourcesUtil.DefType.DIMEN,ANDROID_OS_PACKAGE)
        return context.resources.getDimensionPixelSize(resId)
    }

    /**
     *  获取整个屏幕的高度
     * @param context 上下文
     */
    public fun getScreenHeight(context:Context):Int{
        val point = Point()
        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            return wm.currentWindowMetrics.bounds.bottom
        } else {
            wm.defaultDisplay.getRealSize(point)
        }
        return point.y
    }

    /**
     *  获取根布局
     * @param activity activity
     */
    public fun getActivityRootView(activity:Activity):ViewGroup{
        val decorView = activity.window.decorView
        return decorView.findViewById<ViewGroup>(android.R.id.content)
    }

    /**
     *  设置app是否可以操作
     */
    public fun setAppIsCanOperate(isCan:Boolean,activity: Activity){
        if(isCan){
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE)
        }else{
            activity.getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE)
        }
    }

    /**
     *  获取控件在窗口中的位置区域
     * @param view 目标控件
     */
    public fun getViewAbsRect(view: View?): Rect {
        val loc = IntArray(2)
        //获取控件在窗口中的坐标位置，x,y
        view?.getLocationInWindow(loc)
        val rect = Rect()
        rect.set(loc[0],loc[1],loc[0] + (view?.measuredWidth?:0),loc[1] + (view?.measuredHeight?:0))
        return rect
    }

    /**
     *  获取底部状态栏高度
     * @param context 山下文
     */
    public fun getNavigationBarHeight(context: Context): Int {
        val resId = ResourcesUtil.instance.getResourcesId(
            context,
            NAVIGATION_BAR_HEIGHT,
            ResourcesUtil.DefType.DIMEN,
            ANDROID_OS_PACKAGE
        )
        return context.resources.getDimensionPixelSize(resId)
    }

    /**
     *  获取是否存在NavigationBar
     * @param context 上下文
     */
    public fun checkDeviceHasNavigationBar(context: Context): Boolean {
        var hasNavigationBar = false
        val rs: Resources = context.resources
        val id: Int = rs.getIdentifier("config_showNavigationBar", "bool", "android")
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id)
        }
        try {
            val systemPropertiesClass = Class.forName("android.os.SystemProperties")
            val m: Method = systemPropertiesClass.getMethod("get", String::class.java)
            val navBarOverride = m.invoke(systemPropertiesClass, "qemu.hw.mainkeys") as String
            if ("1" == navBarOverride) {
                hasNavigationBar = false
            } else if ("0" == navBarOverride) {
                hasNavigationBar = true
            }
        } catch (e: Exception) {
        }
        return hasNavigationBar
    }

    /**
     *  设置屏幕方向
     * @param activity Activity
     * @param mScreenOrientationType 屏幕方向
     */
    public fun setScreenOrientation(activity:Activity,mScreenOrientationType:ScreenOrientationType){
        when(mScreenOrientationType){
            ScreenOrientationType.LANDSCAPE ->{//竖向
                activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
            }
            ScreenOrientationType.PORTRAIT -> {//横向
                activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
            }
        }
    }

    /**
     *  获取屏幕方向
     * @param activity Activity
     */
    public fun getScreenOrientation(activity:Activity):ScreenOrientationType{
        when(activity.requestedOrientation){
            ActivityInfo.SCREEN_ORIENTATION_PORTRAIT -> {
                return ScreenOrientationType.LANDSCAPE
            }
            ActivityInfo.SCREEN_ORIENTATION_PORTRAIT -> {
                return ScreenOrientationType.PORTRAIT
            }
            else ->{
                return ScreenOrientationType.UNKNOWN
            }
        }
    }

    /**
     *  通过view获取Activity
     * @param view 控件
     */
    public fun getActivity(view:View?):Activity?{
        var context = view?.context
        while (context is ContextWrapper){
            if(context is Activity){
                return context
            }else{
                context = (context as ContextWrapper).baseContext
            }
        }
        return null
    }



    public fun dispatchTakePictureIntent(activity:Activity) {
        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
            takePictureIntent.resolveActivity(activity.packageManager)?.also {
                activity.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
            }
        }
    }

    val REQUEST_TAKE_PHOTO = 1

    public fun dispatchTakePictureIntent2(activity: Activity,photoFile:File) {
        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
            // Ensure that there's a camera activity to handle the intent
            takePictureIntent.resolveActivity(activity.packageManager)?.also {
                // Create the File where the photo should go
//                val photoFile: File? = try {
//                    createImageFile(activity)
//                } catch (ex: IOException) {
//                    LogUtil.E("创建文件失败")
//                    null
//                }
                // Continue only if the File was successfully created
                photoFile?.also {
                    val photoURI: Uri = FileProvider.getUriForFile(
                        activity,
                        "com.example.android.fileprovider",
                        it
                    )
                    LogUtil.E("photoUri: "+photoURI)
//                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                    activity.startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO)
//                    galleryAddPic(activity,photoFile.absolutePath)
                }
            }
        }
    }

    public fun galleryAddPic(context:Context,currentPhotoPath:String) {
        Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE).also { mediaScanIntent ->
            val f = File(currentPhotoPath)
            mediaScanIntent.data = Uri.fromFile(f)
            context.sendBroadcast(mediaScanIntent)
            LogUtil.E("gallery add pic")
        }
    }

    lateinit var currentPhotoPath: String

    @Throws(IOException::class)
    public fun createImageFile(context:Context): File {
        // Create an image file name
        val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
        val storageDir: File = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) as File
        return File.createTempFile(
            "JPEG_${timeStamp}_", /* prefix */
            ".jpg", /* suffix */
            storageDir /* directory */
        ).apply {
            // Save a file: path for use with ACTION_VIEW intents
            currentPhotoPath = absolutePath
        }
    }

    /**
     *  查询指定的APP
     * @param context 上下文
     * @param queryAppPkg 需要查询的指定的APP
     */
    public fun queryAssignApp(context:Context?,queryAppPkg:String): PackageInfo? {
        val allApp = queryAllApp(context)
        if(allApp==null){
            return null
        }
        for (i in allApp.indices) {
            if (allApp[i].packageName.equals(queryAppPkg))
                return allApp[i]
        }
        return null
    }

    /**
     *  查询手机里面的所有的APP
     * @param context 上下文
     */
    public fun queryAllApp(context:Context?): List<PackageInfo>? {
        val packageManager: PackageManager? = context?.packageManager
        val pinfo: List<PackageInfo> ?= packageManager?.getInstalledPackages(0)
        if(pinfo?.indices==null){
            return null
        }else{
            return pinfo
        }

    }

    /**
     *  判断控件是否已经存在app布局中
     * @param view 控件
     */
    public fun isExitAppLayout(view:View?):Boolean{
        if(view?.windowToken==null){
            return false
        }
        return true
    }

    /**
     *  获取UUID
     */
    public fun getUUID():String{
        return UUID.randomUUID().toString()
    }

    /**
     *  复制到剪切板
     * @param textToCopy 要复制到剪切板到内容
     * @param label 这次复制的label
     */
    fun copyTextToClipboard(context: Context, textToCopy: String, label: String = "copy text") {
        val clipboard =
            (context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager)
        val clip: ClipData = ClipData.newPlainText(label, textToCopy)
        clipboard.setPrimaryClip(clip)
    }


    enum class ScreenOrientationType{
        PORTRAIT,//屏幕竖向
        LANDSCAPE, // 屏幕横向
        UNKNOWN, // 未知
    }
}